package com.udaos.common.util;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.nutz.http.Http;
import org.nutz.http.HttpException;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;

public class UrlUtil {

	/**
	 * 将参数组合到url中
	 * 
	 * @param url
	 * @param params
	 * @param encoding
	 * @return
	 */
	public static String assembleUrlAndParams(String url, Map<String, Object> params, String encoding) {
		StringBuilder sb = new StringBuilder(url);
		try {
			if (null != params && params.size() > 0) {
				sb.append(url.indexOf('?') > 0 ? '&' : '?');
				for (Entry<String, Object> en : params.entrySet()) {
					final String key = en.getKey();
					Object val = en.getValue();
					if (val == null)
						val = "";
					Lang.each(val, new Each<Object>() {
						public void invoke(int index, Object ele, int length)
								throws ExitLoop, ContinueLoop, LoopException {
							sb.append(Http.encode(key, encoding)).append('=').append(Http.encode(ele, encoding))
									.append('&');
						}
					});
				}
			}
			return sb.toString();
		} catch (Exception e) {
			throw new HttpException(sb.toString(), e);
		}

	}

	/**
	 * 获取请求的完整url,例如:http://www.udaos.com/weixin/index?wxid=wx233dss209210k&key=1
	 * 
	 * @param req
	 * @return
	 */
	public static String getWholeUrl(HttpServletRequest req) {
		String qryStr = req.getQueryString();
		return req.getRequestURL().append(StringUtil.isNullOrEmpty(qryStr) ? "" : "?" + qryStr).toString();
	}

	/**
	 * 获取网站根目录的url,例如:http://www.udaos.com/weixin/
	 * 
	 * @param req
	 * @return
	 */
	public static String getRootPath(HttpServletRequest req) {
		StringBuilder sb = new StringBuilder();
		int port = req.getServerPort();
		String portStr = port == 80 ? "" : ":" + port;
		sb.append(req.getScheme()).append("://").append(req.getServerName()).append(portStr)
				.append(req.getContextPath());
		return sb.toString();
	}
}
